package com.study_online.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Properties;
import java.util.Random;

/**
 * 发邮件工具类
 */
public final class MailUtils {
    private static final String USER = "949952653@qq.com"; // 发件人称号，同邮箱地址
    private static final String PASSWORD = "bgyvftrxmegcbeec"; // 如果是qq邮箱可以使户端授权码，或者登录密码
    //qq:bgyvftrxmegcbeec  163:KNJKNMGZUADGRTMJ  syuan_y520@163.com

    /**
     * @param to    收件人邮箱
     * @param text  邮件正文
     * @param title 标题
     */
    /* 发送验证信息的邮件 */
    public static boolean sendMail(String to, String text, String title) {
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");

            // 发件人的账号
            props.put("mail.user", USER);
            //发件人的密码
            props.put("mail.password", PASSWORD);

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
//
//            if (to != null && !"".equals(to))
//                //to为前台传过来的收件人字符串集合，多个收件人以“,”间隔
//                message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(
//                        MimeUtility.encodeText(RecieverUtil.formatAddressWithChinese(to))));
            // 设置发件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject(title);

            // 设置邮件的内容体
            message.setContent(text, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            System.out.println("验证码发送成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
//            System.out.println("验证码发送失败");
        }
        return false;
    }

    public static void main(String[] args) throws Exception { // 做测试用
//        for (int i = 0; i < 8; i++) {
//            MailUtils.sendMail("2279272902@qq.com","你好，这是一封测试邮件，无需回复。","测试邮件");
//            System.out.println("发送成功");
        //      }

//        MailUtils.sendMail("2841925829@qq.com", "你好，这是一封测试邮件，无需回复。", "测试邮件");
//        System.out.println("发送成功");
 //       String s = sendMail("484892640@qq.com");
        sendMail("2315330301@qq.com");
//        System.out.println(s);
    }

    /**
     * 邮箱验证码
     *
     * @param email
     * @return
     */
    public static String sendMail(String email) {

        String str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPADSFGHJKLZXCVBNM1234567890";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            char a = str.charAt(random.nextInt(62));
            //将c放入到StringBuffer中去
            code.append(a);
        }
        //System.out.println(code);
        String text = "你好!\n" +
                "\n" +
                "感谢你注册在线学习平台。\n" +
                "本次注册的邮箱为：" + email + "。请回填如下4位验证码："+
                "\n" +code.toString();
        System.out.println(text);
        MailUtils.sendMail(email, text, "用户注册验证码");
        return code.toString();
    }

}
